package tk.winshu.shortestpath.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author winshu
 * @date 2015年2月7日
 */
public class FileUtil {

    private static final String CHARSET = "UTF-8";
    private static final Logger log = LoggerFactory.getLogger(FileUtil.class.getName());

    /**
     * 可以从Jar包内部加载
     */
    private static String loadFrom(InputStream input) {
        BufferedReader reader = null;
        try {
            StringBuilder data = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(input, CHARSET));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
            return data.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 从外部路径加载
     */
    public static String loadFrom(String path) {
        try {
            return loadFrom(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static void saveTo(String path, String data) {
        OutputStreamWriter writer = null;
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(path);
            writer = new OutputStreamWriter(output, CHARSET);
            writer.write(data);
            writer.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
